﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.Exceptions.Database;
using BSCMFF.Core;
using BSCMFF.Web.UserControls.Evaluation;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Web.UserControls.Selections;

namespace BSCMFF.Web.Pages.Evaluation_Setup
{
    public partial class AssignEmployeeEvaluation_CustomForm : MultiLanguagePage
    {
        private static int countToAssign = 0;
        private int countAssigned = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (IsPostBack)
            //{
            //    int evalID = Int32.Parse(RadComboBoxEvaluations.SelectedValue);

            //    BSCEntities context = new BSCEntities();

            //    List<User> users = (from eu in context.Evaluation_Evaluator_Employee.Include("User.SBU")
            //                        where eu.Evaluation_FK == evalID //28
            //                        select eu.User).ToList();

            //    RadGridAssignedEmployees.DataSource = users;
            //    RadGridAssignedEmployees.DataBind();
            //}

            if (!IsPostBack && Request.QueryString["EvaluationID"] != null)
            {
                EvalSelection.PublicSelectedValue = Int32.Parse(Request.QueryString["EvaluationID"]);
                PopulateAlreadyAssignedEmployees(EvalSelection.PublicSelectedValue.ToString());
            }

            if (IsPostBack)
            {

                PopulateAlreadyAssignedEmployees(EvalSelection.PublicSelectedValue.ToString());//("28");

                PersistToAssignEmployees();
            }
            else
            {
                countToAssign = 0;
                Session.Remove("tempAEE");
            }
        }

        private void PersistToAssignEmployees()
        {
            if (Session["tempAee"] != null)
            {
                List<AssignEmployeeEvaluator> tempAEE = Session["tempAee"] as List<AssignEmployeeEvaluator>;
                //EmployeeSimpleSelection
                for (int i = 0; i < tempAEE.Count; ++i)
                {
                    AssignEmployeeEvaluator pAEE = LoadControl("~/UserControls/Evaluation/AssignEmployeeEvaluator.ascx") as AssignEmployeeEvaluator;
                    pAEE.ID = tempAEE[i].ID;
                    pAEE.Employee = tempAEE[i].Employee;
                    pAEE.DataBind();
                    //if (tempAEE[i].EvaluatorID != null)
                    //{
                    //pAEE.EvaluatorID = tempAEE[i].EvaluatorID;
                    //}
                    PlaceHolderAssignNew.Controls.Add(pAEE);
                }
            }
            //for (int i = 0; i < countToAssign; ++i)
            //{
            //    AssignEmployeeEvaluator aee = LoadControl("~/UserControls/Evaluation/AssignEmployeeEvaluator.ascx") as AssignEmployeeEvaluator;
            //    aee.ID = "AEE" + (-i).ToString();

            //    PlaceHolderAssignNew.Controls.Add(aee);
            //}
        }

        protected void RadComboBoxEvaluations_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            //PopulateAlreadyAssignedEmployees(RadComboBoxEvaluations.SelectedValue);//("28");
            
        }

        private void PopulateAlreadyAssignedEmployees(string evaluationID)
        {
            int evalID = Int32.Parse(evaluationID);

            if (evalID == 0)
            {
                PanelAlreadyAssignedEmployees.Visible = false;
                PanelAssignNewEmployees.Visible = false;
                EGS.Visible = false;
                return;
            }

            EGS.Visible = true;

            BSCEntities context = new BSCEntities();


            //List<User> users = (from eu in context.Evaluation_Evaluator_Employee.Include("User.SBU").Include("User2")
            //                    where eu.Evaluation_FK == evalID
            //                    select eu.User).ToList();

            List<Evaluation_Evaluator_Employee> eees = 
                                (from eee in context.Evaluation_Evaluator_Employee.Include("User")//.Include("User.SBU")//.Include("User.User2")
                                where eee.Evaluation_FK == evalID
                                select eee).ToList();

            //users[0].ma

            //RadGridAlreadyAssignedEmployees.Items
            if (eees.Count != 0)
            {
                //RadGridAlreadyAssignedEmployees.DataSource = users;
                //RadGridAlreadyAssignedEmployees.DataBind();

                foreach (Evaluation_Evaluator_Employee ee in eees)
                {
                    //foreach (Evaluation_Evaluator_Employee storedEEE in u.Evaluation_Evaluator_Employee)
                    //{
                    
                        AssignEmployeeEvaluator aee = LoadControl("~/UserControls/Evaluation/AssignEmployeeEvaluator.ascx") as AssignEmployeeEvaluator;
                    

                        aee.EEEID = ee.ID; //u.Evaluation_Evaluator_Employee.FirstOrDefault().ID;
                        aee.ID = "AEE" + aee.EEEID.ToString();
                        aee.LinkButtonDeleteEvent += new EventHandler(aee_LinkButtonDeleteEvent);
                        aee.Employee = ee.User;
                        aee.EvaluatorAssignedID = ee.Evaluator_FK;
                        aee.DataBind();

                        //TableEmployees.Rows.Add(aee);

                        PlaceHolderAlreadyAssigned.Controls.Add(aee);

                        ++countAssigned;
                    //}
                }
                PanelAlreadyAssignedEmployees.Visible = true;
                RadButtonConfirm.Visible = true;
            }
            else
            {
                PanelAlreadyAssignedEmployees.Visible = false;
            }
            //radgri
        }

        void aee_LinkButtonDeleteEvent(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();

            int eeeID = ((AssignEmployeeEvaluator)sender).EEEID;

            Evaluation_Evaluator_Employee eee = (from ee in context.Evaluation_Evaluator_Employee
                                                 where ee.ID == eeeID
                                                 select ee).SingleOrDefault();
            //delete evaluation data

            EvaluationManager em = new EvaluationManager();
            em.DeleteEvaluationEvaluatorEmployee(eeeID);

            context.DeleteObject(eee);
            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new InconsistentDatabaseException("Couldn't delete evaluation assignment");
            }

            AssignEmployeeEvaluator toDelete = ((AssignEmployeeEvaluator)PlaceHolderAlreadyAssigned.FindControl("AEE" + eeeID));
            PlaceHolderAlreadyAssigned.Controls.Remove(toDelete);

            //PopulateAlreadyAssignedEmployees(RadComboBoxEvaluations.SelectedValue);
        }

        protected void RadButtonPreviewUsers_Click(object sender, EventArgs e)
        {
            countToAssign = 0;
            BSCEntities context = new BSCEntities();

            List<User> previewUsers = new List<User>();
            List<AssignEmployeeEvaluator> tempAEE = new List<AssignEmployeeEvaluator>();

            int previewAEEID=  0;
            foreach (RadListBoxItem rlbi in EGS.RadListBoxSelectedEmployees.Items)
            {
                int userID = Int32.Parse(rlbi.Value);
                User user = (from u in context.Users
                             where u.ID == userID
                             select u).FirstOrDefault();
                //previewUsers.Add(user);

                AssignEmployeeEvaluator aee = LoadControl("~/UserControls/Evaluation/AssignEmployeeEvaluator.ascx") as AssignEmployeeEvaluator;
                aee.ID = "AEE" + (previewAEEID--);
                aee.ViewStateMode = ViewStateMode.Enabled;
                aee.ButtonDeleteVisible = false;
                aee.Employee = user;
                aee.EvaluatorAssignedID = user.Manager_FK == null ? 0 : (int)user.Manager_FK;
                aee.DataBind();

                //TableEmployees.Rows.Add(aee);

                PlaceHolderAssignNew.Controls.Add(aee);
                tempAEE.Add(aee);
                ++countToAssign;
            }

            PanelAssignNewEmployees.Visible = true;
            RadButtonConfirm.Visible = true;

            if (Session["tempAEE"] == null)
            {
                Session.Add("tempAEE", tempAEE);
            }
            else
            {
                Session["tempAEE"] = tempAEE;
            }

            //RadGridToAssignEmployees.DataSource = previewUsers; //previewEEE;
            //RadGridToAssignEmployees.DataBind();

            //try
            //{
            //    context.SaveChanges();
            //}
            //catch
            //{
            //    throw new InconsistentDatabaseException("Couldn't assign Employees");
            //}
        }


        protected void RadButtonConfirm_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();

            List<Evaluation_Evaluator_Employee> previewEEE = new List<Evaluation_Evaluator_Employee>();

            foreach (Control c in PlaceHolderAssignNew.Controls)
            {
                if (c.GetType().BaseType.Name == "AssignEmployeeEvaluator")
                {
                    AssignEmployeeEvaluator aee = (AssignEmployeeEvaluator)c;
                    
                    Evaluation_Evaluator_Employee eee = new Evaluation_Evaluator_Employee();
                    eee.Employee_FK = aee.Employee.ID;

                    if (aee.EvaluatorID == 0)
                    //((RadComboBox)((EmployeeSimpleSelection)PlaceHolderAssignNew.Controls[7].Controls[5]).Controls[1]).SelectedValue
                    //if(((RadComboBox)((EmployeeSimpleSelection)PlaceHolderAssignNew.Controls[7].Controls[5]).Controls[1]).SelectedValue == "0")
                    //{
                    
                    {
                        LabelError.Text = "Not All Employees Have Evaluator Assigned";
                        return;
                    }
                    eee.Evaluator_FK = (int)aee.EvaluatorID;
                    eee.Evaluation_FK = EvalSelection.PublicSelectedValue;

                    
                    context.AddToEvaluation_Evaluator_Employee(eee);
                    //previewEEE.Add(eee);
                }
            }

            foreach (Control c in PlaceHolderAlreadyAssigned.Controls)
            {
                if (c.GetType().BaseType.Name == "AssignEmployeeEvaluator")
                {
                    AssignEmployeeEvaluator aee = (AssignEmployeeEvaluator)c;

                    if (aee.EvaluatorID == 0)
                    {
                        LabelError.Text = "Not All Employees Have Evaluator Assigned";
                        return;
                    }

                    Evaluation_Evaluator_Employee eee = (from ee in context.Evaluation_Evaluator_Employee //new Evaluation_Evaluator_Employee();
                                                         where ee.ID == aee.EEEID
                                                         select ee).SingleOrDefault();

                    //eee.Employee_FK = aee.Employee.ID;

                    
                    eee.Evaluator_FK = (int)aee.EvaluatorID;
                    //eee.Evaluation_FK = EvalSelection.PublicSelectedValue;


                    //context.AddToEvaluation_Evaluator_Employee(eee);
                    //previewEEE.Add(eee);
                }
            }

            LabelError.Text = "";

            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new InconsistentDatabaseException("Couldn't update evaluation assignment");
            }

            foreach (Control c in PlaceHolderAssignNew.Controls)
            {
                if (c.GetType().BaseType.Name == "AssignEmployeeEvaluator")
                {
                    AssignEmployeeEvaluator aee = (AssignEmployeeEvaluator)c;
                    PlaceHolderAssignNew.Controls.Remove(aee);
                    PlaceHolderAlreadyAssigned.Controls.Add(aee);
                }
            }

            //EGS.RadListBoxSelectedEmployees
            Session.Remove("tempAEE");
            PanelAssignNewEmployees.Visible = false;
            Response.Redirect("AssignEmployeeEvaluation_CustomForm.aspx?EvaluationID=" + EvalSelection.PublicSelectedValue);
            //PopulateAlreadyAssignedEmployees(RadComboBoxEvaluations.SelectedValue);
        }
    }
}